package app.server.project.main.service.service.race;

import app.server.project.core.util.GlobalValChangeEvent;
import app.server.project.main.service.bo.event.ClickEvent;
import app.server.project.main.service.db.dao.cfg.RaceCfgDao;
import app.server.project.main.service.db.dao.user.RaceClickDao;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@RequiredArgsConstructor
@Service
public class RaceClickService {

    private final static int RATE = 1000;

    private final RaceClickDao raceClickDao;
    private final RaceCfgDao raceCfgDao;
    private HashMap<Integer, RaceClickTask> raceClickTasks = new HashMap<>();

    @EventListener(value = {ApplicationReadyEvent.class, GlobalValChangeEvent.class})
    public void init() {
        this.raceCfgDao.getAll().forEach(v -> {
            if (!this.raceClickTasks.containsKey(v.getId())) {
                raceClickTasks.put(v.getId(), RaceClickTask.of(this.raceClickDao, v.getId()));
            }
        });
    }

    @EventListener(ClickEvent.class)
    public void onClickEvent(ClickEvent clickEvent) {
        var raceClickTask = raceClickTasks.get(clickEvent.getRaceId());
        if (raceClickTask != null) {
            raceClickTask.add(clickEvent);
        }
    }

    @Scheduled(fixedDelay = RATE)
    public void consume() {
        raceClickTasks.forEach((k, v) -> {
            v.consume();
        });
    }


}
